﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models;
using Tea;
using CronCommon;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading.Tasks;
using Tea.Utils;


namespace DD_Process
{
    class Program
    {
        public static string access_token = "";
        static void Main(string[] args)
        {

            getToken("dingjhuxol34h8gbmr9t","qSn_nHRrU9EsHEoluHutH7oBlgDwSW2Bocm754uIBN8vFu2MOgFQ8lqWi-6Hd5eY");
            long startTime = GetChinaTicks(TimeZoneInfo.ConvertTime(new DateTime(2024, 04,24, 0, 0, 0, 0), TimeZoneInfo.Local));
            //  long endTime = GetChinaTicks( DateTime.Now );
            long endTime = GetChinaTicks(TimeZoneInfo.ConvertTime(new DateTime(2024, 04, 26, 0, 0, 0, 0), TimeZoneInfo.Local));
            string processCode = "PROC-EF6YFCYSO2-PAMKLDOGTUMSHJSIAXAW1-D05QNC2J-22";
            int nextToken = 0;
            int maxResults = 20;
            List<string> result = new List<string>();
            string processIDs;
            if (args.Length > 0)
            {
                Console.WriteLine(args[0].ToString());
                if (args[0].Equals("取实例") == true)
                {
                    startTime = GetChinaTicks(DateTime.Parse(args[1]));
                    endTime = GetChinaTicks(DateTime.Parse(args[2]));

                    processCode = args[3];
                    //   nextToken = int.Parse( args[4]);
                    maxResults = int.Parse(args[4]);

                    result = GetApproveProcessID(startTime, endTime, processCode, nextToken, maxResults);
                    processIDs = String.Join(",", result);

                    SqlHelper.ExecuteSql($"exec  P_插入实例ID '{processCode}','{processIDs}'  ");
                    Environment.Exit(0);
                }
                else if (args[0].Equals("取明细") == true)
                {
                  DataTable dataTable=  SqlHelper.GetDataTable(" select TOP 200 实例ID,模板ID from 钉钉实例清单 a where NOT EXISTS ( SELECT 1  FROM 钉钉模板JSON b  where  a.实例ID=B.实例ID) ");
                    if (dataTable.Rows.Count>0)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        foreach (DataRow dataRow in dataTable.Rows)
                        {
                            stringBuilder.AppendLine($" INSERT INTO 钉钉模板JSON (sJSON, 实例ID,模板ID)  VALUES ('{GetResponseProcessInstanceDetails(dataRow["实例ID"].ToString())}','{dataRow["实例ID"].ToString()}','{dataRow["模板ID"].ToString()}') ;");
                        }
                        // Console.Write(stringBuilder.ToString());  

                        SqlHelper.ExecuteSql(stringBuilder.ToString());
                    }

                 Environment.Exit(0);
                }

                else if (args[0].Equals("批量解析") == true)
                {            
                    SqlHelper.ExecuteSql("P_批量解析实例清单");  
                    Environment.Exit(0);
                }

            }
            else
            {
                result = GetApproveProcessID(startTime, endTime, processCode, nextToken, maxResults);
                processIDs = String.Join(",", result);

                SqlHelper.ExecuteSql($"exec  P_插入实例ID '{processCode}','{processIDs}'  ");

                Environment.Exit(0);

            }
        }

        public static string getToken(string appKey, string appSecret)
        {
            
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.Appkey = appKey;
            req.Appsecret = appSecret;
            req.SetHttpMethod("GET");
            OapiGettokenResponse rsp = client.Execute(req, access_token);
            access_token = rsp.AccessToken;
            return access_token;

        }

        public static AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";

            return new AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client(config);
        }

        public static  ListProcessInstanceIdsResponse GetApproveProcessInstance(long startTime, long endTime, string processCode, int nextToken, int maxResults)
        {
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.ListProcessInstanceIdsHeaders listProcessInstanceIdsHeaders = new AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.ListProcessInstanceIdsHeaders();
            listProcessInstanceIdsHeaders.XAcsDingtalkAccessToken = access_token;
            AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.ListProcessInstanceIdsRequest listProcessInstanceIdsRequest = new AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.ListProcessInstanceIdsRequest
            {
                StartTime = startTime,
                EndTime = endTime,
                ProcessCode = processCode,
                NextToken = nextToken,
                MaxResults = maxResults,
                Statuses = new List<string>
                {
                    "COMPLETED"
                }
            };
            try
            {
                return client.ListProcessInstanceIdsWithOptions(listProcessInstanceIdsRequest, listProcessInstanceIdsHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return null;
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                }
                return null;
            }
        }


          public  static List<string> GetApproveProcessID(long startTime, long endTime, string processCode, int nextToken, int maxResults)
          {
              try
              {
                  List<string> result = new List<string>();

                  ListProcessInstanceIdsResponse listProcessInstanceIdsResponse = GetApproveProcessInstance(startTime, endTime, processCode, nextToken, maxResults);
                  listProcessInstanceIdsResponse.Body.Result.List.ForEach(a => result.Add(a));

                  if (listProcessInstanceIdsResponse.Body.Result.NextToken == null)
                      return result;

                  int nextToken1 = int.Parse(listProcessInstanceIdsResponse.Body.Result.NextToken);

                  //因为一次性最多返回20条，所以还需要再次请求其余的数据
                  while (nextToken1 > 0)
                  {
                      ListProcessInstanceIdsResponse listProcessInstanceIdsResponse1 = GetApproveProcessInstance(startTime, endTime, processCode, nextToken1, maxResults);
                      listProcessInstanceIdsResponse1.Body.Result.List.ForEach(a => result.Add(a));

                      if (listProcessInstanceIdsResponse1.Body.Result.NextToken != null)
                          nextToken1 = int.Parse(listProcessInstanceIdsResponse1.Body.Result.NextToken);
                      else
                          break;
                  }
                  return result;

              }
              catch (TeaException err)
              {
                  if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                  {
                      // err 中含有 code 和 message 属性，可帮助开发定位问题
                  }
                  return null;
              }
              catch (Exception _err)
              {
                  TeaException err = new TeaException(new Dictionary<string, object>
                  {
                      { "message", _err.Message }
                  });
                  if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                  {
                      // err 中含有 code 和 message 属性，可帮助开发定位问题
                  }
                  return null;
              }
          }

        public static long GetChinaTicks(DateTime dateTime)
        {
            //北京时间相差8小时,TimeZoneInfo.Local本地不太有用
            DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 8, 0, 0, 0), TimeZoneInfo.Local);
            long t = (dateTime.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位   
            return t;
        }


        public static string GetResponseProcessInstanceDetails(string process_instance_ids)
        {
         
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
            req.ProcessInstanceId = process_instance_ids;
            OapiProcessinstanceGetResponse rsp = client.Execute(req, access_token);
            return rsp.Body;
        }
    }
}
